import React, { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { createPageUrl } from "@/utils";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import { DocumentTemplateAPI } from "@/api/DocumentTemplate";

import {
  FileText,
  Plus,
  Edit,
  Copy,
  Trash2,
  Star,
  Search,
  Download,
  RefreshCw,
  AlertTriangle,
  WifiOff,
  ChevronLeft,
  ChevronRight,
  MoreHorizontal,
} from "lucide-react";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import DocumentTemplatePreview from "../components/document-templates/DocumentTemplatePreview";
import TemplateBasicInfoForm from "../components/document-templates/TemplateBasicInfoForm";
import VariableReferenceGuide from "../components/document-templates/VariableReferenceGuide";
import DocumentImporter from "../components/document-templates/DocumentImporter";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { Card } from "@/components/ui/card";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Skeleton } from "@/components/ui/skeleton";

export default function DocumentTemplates() {
  const [templates, setTemplates] = useState([]);
  const [isLoading, setIsLoading] = useState(true);
  const [searchTerm, setSearchTerm] = useState("");
  const [filterType, setFilterType] = useState("all");
  const [previewTemplate, setPreviewTemplate] = useState(null);
  const [showCreateModal, setShowCreateModal] = useState(false);
  const [editingTemplateInfo, setEditingTemplateInfo] = useState(null);
  const [showPreview, setShowPreview] = useState(false);
  const [isFullscreen, setIsFullscreen] = useState(false);
  const [showVariableGuide, setShowVariableGuide] = useState(false);
  const [showImporter, setShowImporter] = useState(false);
  const [importingTemplateId, setImportingTemplateId] = useState(null); // 新增：分页相关状态

  const [currentPage, setCurrentPage] = useState(1);
  const [itemsPerPage, setItemsPerPage] = useState(10);
  const [totalItems, setTotalItems] = useState(0); // 错误处理相关状态

  const [error, setError] = useState(null);
  const [retryCount, setRetryCount] = useState(0);
  const [isRetrying, setIsRetrying] = useState(false);

  const navigate = useNavigate(); // 修改：添加分页参数到数据加载

  useEffect(() => {
    loadTemplates();
  }, [currentPage, itemsPerPage, filterType]); // 带重试机制的数据加载函数（添加分页支持）

  const loadTemplates = async (isRetry = false) => {
    if (isRetry) {
      setIsRetrying(true);
      setError(null);
    } else {
      setIsLoading(true);
      setError(null);
    }

    try {
      if (isRetry && retryCount > 0) {
        await new Promise((resolve) =>
          setTimeout(resolve, Math.min(2000 * retryCount, 10000))
        );
      } // 计算分页参数
      const skip = (currentPage - 1) * itemsPerPage;
      const limit = itemsPerPage;
      const result = await DocumentTemplateAPI.getList({
        sort: "-created_date",
        skip,
        limit, // 添加搜索条件
        ...(searchTerm && { search: searchTerm }), // 添加类型筛选条件
        ...(filterType !== "all" && { templateType: filterType }),
      });

      const data = result.data || []; // 假设API返回总条数，否则需要额外请求
      setTotalItems(result.total || data.length);
      setTemplates(data);
      setError(null);
      setRetryCount(0);
      console.log(`成功加载模板数据: 第${currentPage}页，共${data.length}条`);
    } catch (error) {
      console.error("加载模板失败:", error);
      const errorMessage = error.message || "未知错误";
      const isNetworkError =
        errorMessage.includes("500") ||
        errorMessage.includes("timeout") ||
        errorMessage.includes("ServerSelectionTimeoutError") ||
        errorMessage.includes("No replica set members") ||
        (error.name === "TypeError" &&
          error.message.includes("Failed to fetch"));

      setError({
        message: errorMessage,
        isNetworkError,
        canRetry: true,
      });

      if (!isRetry) {
        setTemplates([]);
        setTotalItems(0);
      }
    } finally {
      setIsLoading(false);
      setIsRetrying(false);
    }
  }; // 手动重试函数

  const handleRetry = () => {
    setRetryCount((prev) => prev + 1);
    loadTemplates(true);
  }; // 自动重试函数

  useEffect(() => {
    if (error && error.isNetworkError && retryCount < 3) {
      const timer = setTimeout(() => {
        console.log(`自动重试第 ${retryCount + 1} 次...`);
        handleRetry();
      }, 5000 + retryCount * 2000);

      return () => clearTimeout(timer);
    }
  }, [error, retryCount]); // 搜索处理（重置到第一页）

  const handleSearch = (term) => {
    setSearchTerm(term);
    setCurrentPage(1); // 搜索时重置到第一页
  }; // 筛选类型处理（重置到第一页）

  const handleFilterChange = (type) => {
    setFilterType(type);
    setCurrentPage(1); // 筛选时重置到第一页
  };

  const handleCreateNew = () => {
    setShowCreateModal(true);
  };

  const handleEditContent = (template) => {
    if (!template || !template.id) {
      console.error("模板ID无效:", template);
      alert("模板ID无效，无法编辑");
      return;
    }
    navigate(createPageUrl(`DocumentTemplateEditorPage?id=${template.id}`));
  };

  const handleEditInfo = (template) => {
    setEditingTemplateInfo(template);
  };

  const handleCopy = async (template) => {
    try {
      const newTemplate = {
        ...template,
        name: `${template.name} (副本)`,
        code: `${template.code}_copy_${Date.now()}`,
        isDefault: false,
        version: "1.0",
        templateContent: template.templateContent || { sections: [] },
      };
      delete newTemplate.id;
      delete newTemplate.created_date;
      delete newTemplate.updatedDate;
      delete newTemplate.createdBy;

      const createdTemplate = await DocumentTemplateAPI.create(newTemplate);
      console.log("创建副本成功:", createdTemplate);
      loadTemplates();
    } catch (error) {
      console.error("复制模板失败:", error);
      alert("复制模板失败: " + (error.message || "未知错误"));
    }
  };

  const handleDelete = async (template) => {
    if (!confirm(`确定要删除模板"${template.name}"吗？`)) return;

    try {
      await DocumentTemplateAPI.delete(template.id); // 如果当前页是最后一页且删除后没有数据了，返回上一页
      if (templates.length === 1 && currentPage > 1) {
        setCurrentPage((prev) => prev - 1);
      } else {
        loadTemplates();
      }
    } catch (error) {
      console.error("删除模板失败:", error);
      alert("删除模板失败: " + (error.message || "未知错误"));
    }
  };

  const handleSetDefault = async (template) => {
    try {
      const otherDefaults = templates.filter(
        (t) =>
          t.templateType === template.templateType &&
          t.isDefault &&
          t.id !== template.id
      );

      for (const defaultTemplate of otherDefaults) {
        await DocumentTemplateAPI.update(defaultTemplate.id, {
          isDefault: false,
        });
      }

      await DocumentTemplateAPI.update(template.id, { isDefault: true });
      loadTemplates();
    } catch (error) {
      console.error("设置默认模板失败:", error);
      alert("设置默认模板失败: " + (error.message || "未知错误"));
    }
  };

  const handlePreview = (template) => {
    setPreviewTemplate(template);
    setShowPreview(true);
    setIsFullscreen(false);
  };

  const handleCreateSubmit = async (templateData) => {
    try {
      console.log("创建模板，数据:", templateData);

      if (!templateData.name || !templateData.name.trim()) {
        throw new Error("模板名称不能为空");
      }

      if (!templateData.templateType) {
        throw new Error("请选择模板类型");
      }
      const res = await DocumentTemplateAPI.create({
        ...templateData,
        templateContent: { markdown: "" },
        isActive: true,
        isDefault: false,
      });
      const newTemplate = res.data;
      console.log("模板创建成功:", newTemplate);
      setShowCreateModal(false); // 创建成功后返回第一页
      setCurrentPage(1);
      loadTemplates();
    } catch (error) {
      console.error("创建模板失败:", error);

      let errorMessage = "创建模板失败";
      if (error.message) {
        errorMessage += ": " + error.message;
      }
      if (error.response?.data?.message) {
        errorMessage += " (" + error.response.data.message + ")";
      }

      alert(errorMessage);
    }
  }; // 处理模板导入更新的入口

  const handleImportToTemplate = (template) => {
    setImportingTemplateId(template.id);
    setShowImporter(true);
  }; // 处理从导入器创建或更新模板完成的回调

  const handleImportComplete = () => {
    setShowImporter(false);
    setImportingTemplateId(null);
    loadTemplates();
  };

  const handleUpdateInfoSubmit = async (templateData) => {
    if (!editingTemplateInfo) return;
    try {
      if (!templateData.name || !templateData.name.trim()) {
        throw new Error("模板名称不能为空");
      }

      await DocumentTemplateAPI.update(editingTemplateInfo.id, templateData);
      setEditingTemplateInfo(null);
      loadTemplates();
    } catch (error) {
      console.error("更新模板信息失败:", error);

      let errorMessage = "更新失败";
      if (error.message) {
        errorMessage += ": " + error.message;
      }

      alert(errorMessage);
    }
  };

  const handleClosePreview = () => {
    setShowPreview(false);
    setPreviewTemplate(null);
    setIsFullscreen(false);
  }; // 关闭导入器时重置状态

  const handleCloseImporter = () => {
    setShowImporter(false);
    setImportingTemplateId(null);
  }; // 分页控制函数

  const handlePageChange = (page) => {
    if (page < 1 || page > totalPages) return;
    setCurrentPage(page); // 滚动到表格顶部
    document
      .querySelector(".overflow-x-auto")
      ?.scrollIntoView({ behavior: "smooth" });
  };

  const handleItemsPerPageChange = (count) => {
    setItemsPerPage(count);
    setCurrentPage(1); // 改变每页条数时重置到第一页
  }; // 计算总页数

  const totalPages = Math.ceil(totalItems / itemsPerPage) || 1;

  const currentTemplates = templates;

  const getTypeLabel = (type) => {
    const labels = {
      constructionScheme: "施工方案",
      emergencyPlan: "应急预案",
      workReport: "工作报告",
      safetyAnalysis: "安全分析",
      wordTemplate: "Word模板",
    };
    return labels[type] || type;
  };

  const renderError = () => (
    <Card className="text-center py-12">
      <div className="space-y-4">
        {error.isNetworkError ? (
          <WifiOff className="w-16 h-16 text-red-300 mx-auto" />
        ) : (
          <AlertTriangle className="w-16 h-16 text-red-300 mx-auto" />
        )}
        <div>
          <h3 className="text-lg font-semibold text-gray-900 mb-2">
            {error.isNetworkError ? "网络连接问题" : "加载失败"}
          </h3>
          <p className="text-gray-500 mb-4">
            {error.isNetworkError
              ? "数据库连接暂时不稳定，请稍后重试"
              : error.message}
          </p>
        </div>
        <div className="flex justify-center gap-3">
          <Button
            onClick={handleRetry}
            disabled={isRetrying || retryCount >= 3}
            className="bg-blue-600 hover:bg-blue-700"
          >
            {isRetrying ? (
              <>
                <RefreshCw className="w-4 h-4 mr-2 animate-spin" />
                重试中... {retryCount > 0 && `(${retryCount}/3)`}
              </>
            ) : (
              <>
                <RefreshCw className="w-4 h-4 mr-2" />
                重试
              </>
            )}
          </Button>

          <Button variant="outline" onClick={() => window.location.reload()}>
            刷新页面
          </Button>
        </div>
      </div>
    </Card>
  ); // 渲染加载状态的表格行

  const renderLoadingRows = () => {
    return Array(Math.min(itemsPerPage, 5))
      .fill(0)
      .map((_, index) => (
        <TableRow key={`loading-${index}`}>
          <TableCell>
            <Skeleton className="h-6 w-[200px]" />
          </TableCell>

          <TableCell>
            <Skeleton className="h-6 w-[250px]" />
          </TableCell>

          <TableCell>
            <Skeleton className="h-6 w-[80px]" />
          </TableCell>

          <TableCell>
            <Skeleton className="h-6 w-[200px]" />
          </TableCell>
          <TableCell>
            <Skeleton className="h-6 w-[100px]" />
          </TableCell>
        </TableRow>
      ));
  }; // 渲染分页控件

  const renderPagination = () => (
    <div className="flex flex-col sm:flex-row items-center justify-between gap-4 px-4 py-3 border-t">
      <div className="text-sm text-gray-500">
        共 {totalItems} 条数据，显示
        {(currentPage - 1) * itemsPerPage + 1} 到
        {Math.min(currentPage * itemsPerPage, totalItems)} 条
      </div>
      <div className="flex items-center gap-2">
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <Button variant="outline" size="sm" className="h-8">
              每页 {itemsPerPage} 条
              <MoreHorizontal className="ml-2 h-4 w-4" />
            </Button>
          </DropdownMenuTrigger>
          <DropdownMenuContent align="end">
            {[5, 10, 20, 50].map((count) => (
              <DropdownMenuItem
                key={count}
                onClick={() => handleItemsPerPageChange(count)}
              >
                {count} 条/页
              </DropdownMenuItem>
            ))}
          </DropdownMenuContent>
        </DropdownMenu>
        <div className="flex items-center gap-1">
          <Button
            variant="outline"
            size="icon"
            className="h-8 w-8"
            onClick={() => handlePageChange(currentPage - 1)}
            disabled={currentPage === 1}
          >
            <ChevronLeft className="h-4 w-4" />
            <span className="sr-only">上一页</span>
          </Button>
          {Array.from({ length: Math.min(5, totalPages) }, (_, i) => {
            let pageNum;
            if (totalPages <= 5) {
              pageNum = i + 1;
            } else if (currentPage <= 3) {
              pageNum = i + 1;
            } else if (currentPage >= totalPages - 2) {
              pageNum = totalPages - 4 + i;
            } else {
              pageNum = currentPage - 2 + i;
            }
            return (
              <Button
                key={pageNum}
                variant={currentPage === pageNum ? "default" : "outline"}
                size="icon"
                className="h-8 w-8"
                onClick={() => handlePageChange(pageNum)}
              >
                {pageNum}
              </Button>
            );
          })}
          <Button
            variant="outline"
            size="icon"
            className="h-8 w-8"
            onClick={() => handlePageChange(currentPage + 1)}
            disabled={currentPage === totalPages}
          >
            <ChevronRight className="h-4 w-4" />
            <span className="sr-only">下一页</span>
          </Button>
        </div>
      </div>
    </div>
  );

  if (isLoading && templates.length === 0 && !error) {
    return (
      <div className="p-6">
        <div className="text-center py-12">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600 mx-auto mb-4"></div>
          <p>加载模板中...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="p-6 bg-gray-50 min-h-screen">
      <div className="max-w-7xl mx-auto">
        <div className="mb-6">
          <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between mb-4 gap-4">
            <div>
              <h1 className="text-2xl font-bold text-gray-900 flex items-center gap-2">
                <FileText className="w-6 h-6 text-blue-600" />
                文档模板管理
              </h1>
            </div>
            <div className="flex gap-2 w-full sm:w-auto">
              <Button
                onClick={handleCreateNew}
                className="bg-blue-600 hover:bg-blue-700"
              >
                <Plus className="w-4 h-4 mr-2" />
                创建新模板
              </Button>
            </div>
          </div>
          {error && !isLoading && (
            <Alert
              variant={error.isNetworkError ? "default" : "destructive"}
              className="mb-4"
            >
              <AlertTriangle className="h-4 w-4" />
              <AlertTitle>
                {error.isNetworkError ? "连接不稳定" : "加载错误"}
              </AlertTitle>
              <AlertDescription className="flex items-center justify-between">
                <span>
                  {error.isNetworkError
                    ? `正在尝试重新连接 (${retryCount}/3)，部分功能可能受影响。`
                    : error.message}
                </span>
                {!isRetrying && retryCount < 3 && (
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={handleRetry}
                    className="ml-4"
                  >
                    <RefreshCw className="w-4 h-4 mr-1" />
                    重试
                  </Button>
                )}
                {retryCount >= 3 && error.isNetworkError && (
                  <span className="text-sm text-gray-500 ml-4">
                    请检查网络或稍后刷新页面
                  </span>
                )}
              </AlertDescription>
            </Alert>
          )}
          <div className="flex flex-col sm:flex-row gap-4 mb-6">
            <div className="flex-1">
              <div className="relative">
                <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4" />
                <Input
                  placeholder="搜索模板名称或描述..."
                  value={searchTerm}
                  onChange={(e) => handleSearch(e.target.value)}
                  className="pl-10 w-full"
                />
              </div>
            </div>
            <DropdownMenu>
              <DropdownMenuTrigger asChild>
                <Button variant="outline" className="min-w-[160px]">
                  {filterType === "all" ? "所有类型" : getTypeLabel(filterType)}
                  <MoreHorizontal className="ml-2 h-4 w-4" />
                </Button>
              </DropdownMenuTrigger>
              <DropdownMenuContent>
                <DropdownMenuItem onClick={() => handleFilterChange("all")}>
                  所有类型
                </DropdownMenuItem>
                <DropdownMenuSeparator />
                <DropdownMenuItem
                  onClick={() => handleFilterChange("constructionScheme")}
                >
                  施工方案
                </DropdownMenuItem>
                <DropdownMenuItem
                  onClick={() => handleFilterChange("emergencyPlan")}
                >
                  应急预案
                </DropdownMenuItem>
                <DropdownMenuItem
                  onClick={() => handleFilterChange("workReport")}
                >
                  工作报告
                </DropdownMenuItem>
                <DropdownMenuItem
                  onClick={() => handleFilterChange("safetyAnalysis")}
                >
                  安全分析
                </DropdownMenuItem>
                <DropdownMenuItem
                  onClick={() => handleFilterChange("wordTemplate")}
                >
                  Word模板
                </DropdownMenuItem>
              </DropdownMenuContent>
            </DropdownMenu>
          </div>
        </div>
        {error && !isLoading && templates.length === 0 ? (
          renderError()
        ) : currentTemplates.length === 0 ? (
          <Card className="text-center py-12">
            <div>
              <FileText className="w-16 h-16 text-gray-300 mx-auto mb-4" />
              <h3 className="text-lg font-medium text-gray-900 mb-2">
                {searchTerm || filterType !== "all"
                  ? "未找到匹配的模板"
                  : "还没有文档模板"}
              </h3>
              <p className="text-gray-500 mb-4">
                {searchTerm || filterType !== "all"
                  ? "尝试调整搜索条件或筛选器"
                  : "创建第一个文档模板来开始使用"}
              </p>
              {!searchTerm && filterType === "all" && (
                <Button
                  onClick={handleCreateNew}
                  className="bg-blue-600 hover:bg-blue-700"
                >
                  <Plus className="w-4 h-4 mr-2" />
                  创建新模板
                </Button>
              )}
            </div>
          </Card>
        ) : (
          // 表格布局
          <Card>
            <div className="overflow-x-auto">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead className="w-[400px]">模板名称</TableHead>
                    <TableHead>描述</TableHead>
                    <TableHead>版本</TableHead>
                    <TableHead>Word母版</TableHead>
                    <TableHead className="text-right">操作</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {isLoading
                    ? renderLoadingRows()
                    : currentTemplates.map((template) => (
                        <TableRow
                          key={template.id}
                          className="hover:bg-gray-50"
                        >
                          <TableCell className="font-medium">
                            <div className="flex items-center gap-2">
                              {template.name}
                              {template.isDefault && (
                                <Star className="w-4 h-4 text-yellow-500 fill-current" />
                              )}
                              {!template.isActive && (
                                <Badge variant="secondary" className="ml-1">
                                  已禁用
                                </Badge>
                              )}
                            </div>
                          </TableCell>
                          <TableCell>
                            <span className="truncate max-w-[250px]">
                              {template.description || "-"}
                            </span>
                          </TableCell>
                          <TableCell>v{template.version}</TableCell>

                          <TableCell>
                            <div className="flex items-center gap-2">
                              {template.wordTemplateFilename ? (
                                <>
                                  <span
                                    className="truncate max-w-[200px]"
                                    title={template.wordTemplateFilename}
                                  >
                                    {template.wordTemplateFilename}
                                  </span>
                                  {template.wordTemplateUrl && (
                                    <Button
                                      variant="ghost"
                                      size="sm"
                                      className="p-1 h-auto"
                                      onClick={(e) => {
                                        e.stopPropagation();
                                        const link =
                                          document.createElement("a");
                                        link.href = template.wordTemplateUrl;
                                        link.download =
                                          template.wordTemplateFilename ||
                                          "wordTemplate.docx";
                                        link.target = "_blank";
                                        document.body.appendChild(link);
                                        link.click();
                                        document.body.removeChild(link);
                                      }}
                                      title="下载Word模板"
                                    >
                                      <Download className="w-3 h-3" />
                                    </Button>
                                  )}
                                </>
                              ) : (
                                <span className="text-gray-500 text-sm">
                                  未设置
                                </span>
                              )}
                            </div>
                          </TableCell>
                          <TableCell className="text-right">
                            <DropdownMenu>
                              <DropdownMenuTrigger asChild>
                                <Button
                                  variant="ghost"
                                  size="icon"
                                  className="text-slate-400 hover:text-slate-600"
                                >
                                  <MoreHorizontal className="w-4 h-4" />
                                </Button>
                              </DropdownMenuTrigger>
                              <DropdownMenuContent align="end">
                                <DropdownMenuItem
                                  onClick={() => handleEditInfo(template)}
                                >
                                  <Edit className="w-4 h-4 mr-2" />
                                  编辑信息
                                </DropdownMenuItem>
                                <DropdownMenuItem
                                  onClick={() => handleCopy(template)}
                                >
                                  <Copy className="w-4 h-4 mr-2" />
                                  复制
                                </DropdownMenuItem>
                                {!template.isDefault && (
                                  <DropdownMenuItem
                                    onClick={() => handleSetDefault(template)}
                                  >
                                    <Star className="w-4 h-4 mr-2" />
                                    设为默认
                                  </DropdownMenuItem>
                                )}
                                <DropdownMenuSeparator />
                                <DropdownMenuItem
                                  onClick={() => handleDelete(template)}
                                  className="text-red-700"
                                >
                                  <Trash2 className="w-4 h-4 mr-2" />
                                  删除
                                </DropdownMenuItem>
                              </DropdownMenuContent>
                            </DropdownMenu>
                          </TableCell>
                        </TableRow>
                      ))}
                </TableBody>
              </Table>
            </div>
            {!error && totalItems > 0 && renderPagination()}
          </Card>
        )}
        <Dialog open={showCreateModal} onOpenChange={setShowCreateModal}>
          <DialogContent>
            <DialogHeader>
              <DialogTitle>创建新文档模板</DialogTitle>
            </DialogHeader>
            <TemplateBasicInfoForm
              onSubmit={handleCreateSubmit}
              onCancel={() => setShowCreateModal(false)}
            />
          </DialogContent>
        </Dialog>
        <Dialog
          open={!!editingTemplateInfo}
          onOpenChange={() => setEditingTemplateInfo(null)}
        >
          <DialogContent>
            <DialogHeader>
              <DialogTitle>编辑模板基本信息</DialogTitle>
              <DialogDescription>
                修改模板的名称、描述、类型等元数据信息。
              </DialogDescription>
            </DialogHeader>
            <TemplateBasicInfoForm
              template={editingTemplateInfo}
              onSubmit={handleUpdateInfoSubmit}
              onCancel={() => setEditingTemplateInfo(null)}
            />
          </DialogContent>
        </Dialog>
        <Dialog open={showVariableGuide} onOpenChange={setShowVariableGuide}>
          <DialogContent className="max-w-4xl h-[80vh] flex flex-col p-0">
            <VariableReferenceGuide />
          </DialogContent>
        </Dialog>
        {showPreview && (
          <>
            {isFullscreen ? (
              // 全屏模式
              <div className="fixed inset-0 z-50 bg-white">
                <DocumentTemplatePreview
                  template={previewTemplate}
                  onClose={handleClosePreview}
                  isFullscreen={isFullscreen}
                  onToggleFullscreen={() => setIsFullscreen(!isFullscreen)}
                />
              </div>
            ) : (
              // 对话框模式
              <Dialog open={showPreview} onOpenChange={setShowPreview}>
                <DialogContent className="max-w-5xl h-[80vh] flex flex-col p-0">
                  <DialogHeader className="p-6 pb-0">
                    <DialogTitle>
                      模板预览 - {previewTemplate?.name}
                    </DialogTitle>
                  </DialogHeader>
                  <div className="flex-1 h-full overflow-hidden">
                    <DocumentTemplatePreview
                      template={previewTemplate}
                      onClose={handleClosePreview}
                      isFullscreen={isFullscreen}
                      onToggleFullscreen={() => setIsFullscreen(!isFullscreen)}
                    />
                  </div>
                </DialogContent>
              </Dialog>
            )}
          </>
        )}
        <Dialog open={showImporter} onOpenChange={handleCloseImporter}>
          <DialogContent className="max-w-4xl">
            <DialogHeader>
              <DialogTitle>
                {importingTemplateId
                  ? `更新模板 '${
                      templates.find((t) => t.id === importingTemplateId)
                        ?.name || ""
                    }'`
                  : "智能文档导入"}
              </DialogTitle>
              <DialogDescription>
                {importingTemplateId
                  ? "上传新的Word文档来更新现有模板的内容和母版文件，版本号将自动递增。"
                  : "上传现有的施工方案Word文档，系统将自动识别文档结构，并生成可重用的模板和母版文件。"}
              </DialogDescription>
            </DialogHeader>
            <DocumentImporter
              onTemplateCreated={handleImportComplete}
              isUpdatingTemplate={!!importingTemplateId}
              templateName={
                importingTemplateId
                  ? templates.find((t) => t.id === importingTemplateId)?.name
                  : null
              }
              templateId={importingTemplateId}
            />
          </DialogContent>
        </Dialog>
      </div>
    </div>
  );
}
